package icu.lookyousmileface.volatilecode;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author starrysky
 * @title: VolatileUse
 * @projectName Juc_Pro
 * @description: volatile原子性测试
 * @date 2021/1/307:52 上午
 */
public class VolatileShow {
    /**
     * // 不加 volatile 程序就会死循环！
     * // 加 volatile 可以保证可见性
     */
    private  volatile static int num = 0;

    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                Runtime.getRuntime().availableProcessors(),
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        //线程1对内存中num=1的变化不知道
        threadPoolExecutor.execute(() -> {
            while (num == 0) {

            }
        });

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        num = 1;

        System.out.println("num:"+num);

        threadPoolExecutor.shutdown();

    }
}
